<template>
  <Layout>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="px-6 py-4 border-b flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900">我的文章</h1>
          <Link
            href="/posts/create"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 text-sm font-medium"
          >
            写文章
          </Link>
        </div>

        <!-- 统计信息 -->
        <div class="px-6 py-4 border-b bg-gray-50">
          <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div>
              <div class="text-2xl font-bold text-gray-900">{{ stats.total }}</div>
              <div class="text-sm text-gray-500">全部文章</div>
            </div>
            <div>
              <div class="text-2xl font-bold text-green-600">{{ stats.published }}</div>
              <div class="text-sm text-gray-500">已发布</div>
            </div>
            <div>
              <div class="text-2xl font-bold text-yellow-600">{{ stats.draft }}</div>
              <div class="text-sm text-gray-500">草稿</div>
            </div>
            <div>
              <div class="text-2xl font-bold text-blue-600">{{ stats.total_views }}</div>
              <div class="text-sm text-gray-500">总浏览量</div>
            </div>
          </div>
        </div>

        <!-- 筛选栏 -->
        <div class="px-6 py-4 border-b">
          <div class="flex flex-col sm:flex-row gap-4">
            <div class="flex-1">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索文章标题..."
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
            <select
              v-model="statusFilter"
              class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="all">全部状态</option>
              <option value="published">已发布</option>
              <option value="draft">草稿</option>
              <option value="scheduled">定时发布</option>
              <option value="archived">已归档</option>
            </select>
            <select
              v-model="sortBy"
              class="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            >
              <option value="created_at">按创建时间</option>
              <option value="updated_at">按更新时间</option>
              <option value="views_count">按浏览量</option>
              <option value="likes_count">按点赞数</option>
            </select>
          </div>
        </div>

        <!-- 文章列表 -->
        <div class="p-6">
          <div v-if="loading" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            <p class="mt-2 text-gray-500">加载中...</p>
          </div>

          <div v-else-if="filteredPosts.length === 0" class="text-center py-8">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
            </svg>
            <p class="mt-2 text-gray-500">暂无文章</p>
            <Link
              href="/posts/create"
              class="mt-4 inline-block px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
            >
              开始写作
            </Link>
          </div>

          <div v-else class="space-y-4">
            <article
              v-for="post in paginatedPosts"
              :key="post.id"
              class="border rounded-lg p-4 hover:shadow-md transition-shadow"
            >
              <div class="flex justify-between items-start">
                <div class="flex-1">
                  <!-- 文章状态标签 -->
                  <div class="flex items-center space-x-2 mb-2">
                    <span
                      class="px-2 py-1 text-xs font-medium rounded-full"
                      :class="getStatusClass(post.status)"
                    >
                      {{ getStatusText(post.status) }}
                    </span>
                    <span v-if="!post.is_approved && post.status === 'published'" class="px-2 py-1 text-xs bg-yellow-100 text-yellow-800 rounded-full">
                      待审核
                    </span>
                    <span v-if="post.is_featured" class="px-2 py-1 text-xs bg-purple-100 text-purple-800 rounded-full">
                      精选
                    </span>
                    <span v-if="post.is_sticky" class="px-2 py-1 text-xs bg-red-100 text-red-800 rounded-full">
                      置顶
                    </span>
                    <span
                      class="px-2 py-1 text-xs rounded-full"
                      :class="getAccessLevelClass(post.access_level)"
                    >
                      {{ getAccessLevelText(post.access_level) }}
                    </span>
                  </div>

                  <!-- 文章标题 -->
                  <h3 class="text-lg font-semibold text-gray-900 mb-1">
                    <Link
                      v-if="post.status === 'published' && post.is_approved"
                      :href="`/posts/${post.slug}`"
                      class="hover:text-blue-600"
                    >
                      {{ post.title }}
                    </Link>
                    <span v-else>{{ post.title }}</span>
                  </h3>

                  <!-- 文章摘要 -->
                  <p class="text-gray-600 text-sm mb-3 line-clamp-2">
                    {{ post.excerpt || '暂无摘要' }}
                  </p>

                  <!-- 文章信息 -->
                  <div class="flex flex-wrap items-center gap-4 text-sm text-gray-500">
                    <span v-if="post.category">
                      分类: {{ post.category.name }}
                    </span>
                    <span>{{ formatDate(post.created_at) }}</span>
                    <span v-if="post.published_at">
                      发布于: {{ formatDate(post.published_at) }}
                    </span>
                    <div class="flex items-center space-x-3">
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                        {{ post.views_count }}
                      </span>
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                        </svg>
                        {{ post.likes_count }}
                      </span>
                      <span class="flex items-center">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                        </svg>
                        {{ post.comments_count }}
                      </span>
                    </div>
                  </div>

                  <!-- 拒绝原因 -->
                  <div v-if="post.rejected_reason" class="mt-3 p-3 bg-red-50 border border-red-200 rounded-md">
                    <p class="text-sm text-red-800">
                      <strong>审核拒绝原因：</strong>{{ post.rejected_reason }}
                    </p>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="ml-4 flex-shrink-0">
                  <div class="relative" ref="dropdownRefs">
                    <button
                      @click="toggleDropdown(post.id)"
                      class="p-2 text-gray-400 hover:text-gray-600"
                    >
                      <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                        <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                      </svg>
                    </button>

                    <!-- 下拉菜单 -->
                    <div
                      v-if="openDropdown === post.id"
                      class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-10"
                    >
                      <Link
                        :href="`/posts/${post.id}/edit`"
                        class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                      >
                        编辑
                      </Link>
                      <button
                        v-if="post.status === 'draft'"
                        @click="publishPost(post.id)"
                        class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                      >
                        发布
                      </button>
                      <button
                        v-if="post.status === 'published'"
                        @click="unpublishPost(post.id)"
                        class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                      >
                        转为草稿
                      </button>
                      <Link
                        v-if="post.status === 'published' && post.is_approved"
                        :href="`/posts/${post.slug}`"
                        class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                      >
                        查看
                      </Link>
                      <button
                        @click="deletePost(post.id)"
                        class="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-gray-100"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </article>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="mt-6 flex justify-center">
            <nav class="flex space-x-2">
              <button
                @click="currentPage--"
                :disabled="currentPage === 1"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                上一页
              </button>

              <button
                v-for="page in visiblePages"
                :key="page"
                @click="currentPage = page"
                class="px-3 py-2 rounded-md text-sm font-medium"
                :class="currentPage === page
                  ? 'bg-blue-600 text-white'
                  : 'border border-gray-300 text-gray-700 hover:bg-gray-50'"
              >
                {{ page }}
              </button>

              <button
                @click="currentPage++"
                :disabled="currentPage === totalPages"
                class="px-3 py-2 rounded-md border border-gray-300 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                下一页
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { Link, router } from '@inertiajs/inertia-vue3'
import Layout from '@/Components/Layout.vue'
import axios from 'axios'

const loading = ref(false)
const posts = ref([])
const searchQuery = ref('')
const statusFilter = ref('all')
const sortBy = ref('created_at')
const currentPage = ref(1)
const perPage = 10
const openDropdown = ref(null)

const stats = ref({
  total: 0,
  published: 0,
  draft: 0,
  total_views: 0
})

// 过滤后的文章
const filteredPosts = computed(() => {
  let result = [...posts.value]

  // 搜索过滤
  if (searchQuery.value) {
    result = result.filter(p =>
      p.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    result = result.filter(p => p.status === statusFilter.value)
  }

  // 排序
  result.sort((a, b) => {
    const field = sortBy.value
    if (field === 'views_count' || field === 'likes_count') {
      return b[field] - a[field]
    }
    return new Date(b[field]) - new Date(a[field])
  })

  return result
})

// 分页后的文章
const paginatedPosts = computed(() => {
  const start = (currentPage.value - 1) * perPage
  const end = start + perPage
  return filteredPosts.value.slice(start, end)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredPosts.value.length / perPage)
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

const getStatusClass = (status) => {
  const classes = {
    published: 'bg-green-100 text-green-800',
    draft: 'bg-gray-100 text-gray-800',
    scheduled: 'bg-blue-100 text-blue-800',
    archived: 'bg-yellow-100 text-yellow-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const texts = {
    published: '已发布',
    draft: '草稿',
    scheduled: '定时发布',
    archived: '已归档'
  }
  return texts[status] || status
}

const getAccessLevelClass = (level) => {
  const classes = {
    public: 'bg-green-100 text-green-800',
    login_required: 'bg-blue-100 text-blue-800',
    followers_only: 'bg-purple-100 text-purple-800',
    private: 'bg-red-100 text-red-800'
  }
  return classes[level] || 'bg-gray-100 text-gray-800'
}

const getAccessLevelText = (level) => {
  const texts = {
    public: '公开',
    login_required: '需登录',
    followers_only: '仅关注者',
    private: '私密'
  }
  return texts[level] || level
}

const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const toggleDropdown = (postId) => {
  openDropdown.value = openDropdown.value === postId ? null : postId
}

const loadPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/user/posts')
    posts.value = response.data.posts
    stats.value = response.data.stats
  } catch (error) {
    console.error('加载文章失败:', error)
  } finally {
    loading.value = false
  }
}

const publishPost = async (postId) => {
  try {
    await axios.post(`/api/posts/${postId}/publish`)
    await loadPosts()
    openDropdown.value = null
  } catch (error) {
    console.error('发布失败:', error)
    alert('发布失败，请重试')
  }
}

const unpublishPost = async (postId) => {
  try {
    await axios.post(`/api/posts/${postId}/unpublish`)
    await loadPosts()
    openDropdown.value = null
  } catch (error) {
    console.error('操作失败:', error)
    alert('操作失败，请重试')
  }
}

const deletePost = async (postId) => {
  if (!confirm('确定删除这篇文章吗？')) return

  try {
    await axios.delete(`/api/posts/${postId}`)
    await loadPosts()
    openDropdown.value = null
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败，请重试')
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.relative')) {
    openDropdown.value = null
  }
}

onMounted(() => {
  loadPosts()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>